package com.team.ai.tool;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpUtil {
    /**
     * 发送form表单类型的Post请求
     *
     * @param url       发送的url
     * @param headerMap 请求头参数集合 key参数名 value为参数值
     * @param bodyMap   请求参数集合 key参数名 value为参数值
     */
    public static String sendFormPost(String url, Map<String, String> headerMap, Map<String, String> bodyMap) {

        //创建post请求对象
        HttpPost post = new HttpPost(url);
        try {
            //创建参数集合
            List<BasicNameValuePair> list = new ArrayList<>();
            //添加参数
            if (bodyMap != null) {
                for (String str : bodyMap.keySet()
                ) {
                    list.add(new BasicNameValuePair(str, bodyMap.get(str)));
                }
            }
            //把参数放入请求对象，，post发送的参数list，指定格式
            post.setEntity(new UrlEncodedFormEntity(list));

            if (headerMap != null) {
                for (String str : headerMap.keySet()
                ) {
                    post.addHeader(str, headerMap.get(str));
                }
            }

            CloseableHttpClient client = HttpClients.createDefault();
            //启动执行请求，并获得返回值
            CloseableHttpResponse response = client.execute(post);
            //得到返回的entity对象
            HttpEntity entity = response.getEntity();
            //把实体对象转换为string
            String result = EntityUtils.toString(entity);
            //为防止频繁调用一个接口导致接口爆掉，每次调用完成后停留100毫秒
            Thread.sleep(100);
            //返回内容
            return result;
        } catch (Exception e1) {
            e1.printStackTrace();
            return "";
        }
    }

}
